"""
暂定
表名 字段名 字段值 筛选字段[允许多选]
"""
from db.common.db_map import get_db_maps, get_column_by_table
from common.utils import init_item, compare_str, empty
from db.simple.db_query import query


def search(query_str):
    rs = get_fill_result(query_str)
    if rs is not None:
        return rs
    
    if query_str[-1] == '|':
        query_arr = query_str[:len(query_str)-1].split(' ')
        # 执行数据库查询
        return query(query_arr)
        pass
    query_arr = query_str.split(' ')
    if len(query_arr) > 3:
        # 返回field_filter 提示
        return get_filed_filter_column(query_arr[0], query_arr[1], query_arr[2], query_arr[3:])
    return []
    pass


def get_fill_result(query_str):
    query_arr = query_str.split(' ')
    # 表
    if len(query_arr) == 1:
        return get_fill_by_table(query_arr[0])
        pass
    if len(query_arr) == 2:
        return get_fill_by_column(query_arr[0], query_arr[1])
    return None
    pass


def get_fill_by_table(table_name):
    results = []
    table_arr = table_name.split('.')
    db = table_arr[0]
    table_name = '' if len(table_arr) <= 1 else table_arr[1]
    all_tables = get_db_maps()
    for table in all_tables:
        if compare_str(table, table_name) and compare_str(table, db):
            query_str = 'db ' + table
            results.append(init_item(text=table, subtext=query_str, completion=query_str))
    return results
    pass


def get_fill_by_column(table_name, column_name):
    results = []
    all_column = get_column_by_table(table_name)
    for column in all_column:
        if compare_str(column, column_name):
            query_str = "db %s %s" % (table_name, column)
            results.append(init_item(text=column, subtext=query_str, completion=query_str))
    return results
    pass


def get_filed_filter_column(table_name, column_name, value, filed_filter):
    results = []
    all_column = get_column_by_table(table_name)
    last_filed = '' if empty(filed_filter) else filed_filter[-1]
    for column in all_column:
        if compare_str(column, last_filed):
            if column in filed_filter:
                continue
            query_str = "db %s %s %s " % (table_name, column_name, value)
            if empty(filed_filter):
                filed_filter.append(column)
            else:
                filed_filter[-1] = column
            query_str += ' '.join(filed_filter) + ' '
            results.append(init_item(text=column, subtext=query_str, completion=query_str))
    return results
    pass
